package com.xiaobaibai.controller;

import com.xiaobaibai.entity.Announcement;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.IAnnouncementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "公告管理相关接口")
@RequestMapping("/announcement")
@CrossOrigin
public class AnnouncementController {

    @Autowired
    private IAnnouncementService announcementService;

    @GetMapping("/list")
    @ApiOperation("获取公告集合")
    public ResponseFormat getAnnouncementTitle(){
        List<Announcement> list = announcementService.list();
        return ResponseFormat.ok("获取公告集合成功",list);
    }

    @PostMapping("/do-announcement")
    @ApiOperation("添加公告")
    @CacheEvict(value = "announcement",allEntries = true)
    public ResponseFormat addAnnouncement(@RequestBody Announcement announcement){
        boolean flag = announcementService.save(announcement);
        if(!flag)
            return ResponseFormat.failure("添加公告失败");
        return ResponseFormat.ok("添加公告成功",announcement);
    }

    @DeleteMapping("/do-announcement")
    @ApiOperation("删除公告")
    @CacheEvict(value = "announcement",allEntries = true)
    public ResponseFormat deleteAnnouncement(@RequestParam(value = "id")Integer id){
        boolean flag = announcementService.removeById(id);
        if(!flag)
            return ResponseFormat.failure("删除公告失败");
        return ResponseFormat.ok("删除公告成功");
    }

    @PutMapping("/do-announcement")
    @ApiOperation("修改公告")
    @CacheEvict(value = "announcement",allEntries = true)
    public ResponseFormat updateAnnouncement(@RequestBody Announcement announcement){
        boolean flag = announcementService.updateById(announcement);
        if(!flag)
            return ResponseFormat.failure("修改公告失败");
        return ResponseFormat.ok("修改公告成功",announcement);
    }

    @GetMapping("/item/{id}")
    @ApiOperation("获取单个公告的详细信息")
    public ResponseFormat getAnnouncementItem(@PathVariable(value = "id")Integer id){
        Announcement item = announcementService.getById(id);
        return ResponseFormat.ok("获取公告数据成功",item);
    }

}
